<template>
  <div id="dashboard">
    <el-container class="app-container">
      <el-header class="app-header">
        <div class="header-left display-flex">
          <div class="logo-wrap">
            <!-- <img src="../assets/logo.png" alt class="logo" /> -->
          </div>
          <div class="collapse-wrap">
            <i class="el-icon-s-fold" @click="handleCollapse(true)" v-show="!isCollapse"></i>
            <i class="el-icon-s-unfold" @click="handleCollapse(false)" v-show="isCollapse"></i>
          </div>
        </div>
        <div class="header-right">
           <el-dropdown trigger="click" @command="switchLang">
            <p class="lang-text"> {{langText}} <i class="el-icon-arrow-down el-icon--right"></i></p>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item of langOptions" :key="item.value" :command="item.value">
                {{ item.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span style="margin-right:15px;">{{user.AccountName}}</span>
          
          <el-dropdown @command="handleCommand">
            <i class="el-icon-setting header-icon"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="updatePassword">{{$t('changePassword')}}</el-dropdown-item>
              <el-dropdown-item command="signOut">{{$t('retreatSafely')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-container style="height: calc(100% - 60px);">
        <el-aside class="app-aside" style="text-align:left;">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            @open="handleOpen"
            @close="handleClose"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
            style="height:100%;"
            unique-opened
            :collapse="isCollapse"
          >
            <div v-for="nav in navResource" v-bind:key="nav.id">
              <el-submenu :index="nav.index" v-if="nav.children && nav.children.length > 0">
                <template slot="title">
                  <i :class="nav.icon"></i>
                  <span>{{nav.value}}</span>
                </template>
                <el-menu-item
                  :index="item.index"
                  @click="navTo(item.path)"
                  v-for="item in nav.children"
                  :key="item.$index"
                >{{item.value}}</el-menu-item>
              </el-submenu>
              <el-menu-item :index="nav.index" @click="navTo(nav.path)" v-else>
                <i :class="nav.icon"></i>
                <span slot="title">{{nav.value}}</span>
              </el-menu-item>
            </div>
          </el-menu>
        </el-aside>
        <el-main
          class="app-main"
          v-loading="loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
        >
          <router-view />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="500px">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="旧密码" :label-width="formLabelWidth" prop="oldPassword">
          <el-input v-model="ruleForm.oldPassword" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="accountPassword">
          <el-input type="password" v-model="ruleForm.accountPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="confirmPassword">
          <el-input type="password" v-model="ruleForm.confirmPassword" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUpdatePassword">取 消</el-button>
        <el-button type="primary" @click="sureUpdatePassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { signOut, setItem, getItem } from '../script/config/common';
import { menuData } from '../models/fake-data'

export default {
  name: 'dashboard',
  data() {
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.ruleForm.confirmPassword !== '') {
          this.$refs.ruleForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    var checkConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入确认密码'));
      } else if (value !== this.ruleForm.accountPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var validateOldPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'));
      } else {
        callback();
      }
    };
    return {
      navResource: [],
      activeMenu: '1',
      user: {},
      formLabelWidth: '120px',
      dialogFormVisible: false,
      ruleForm: {
        oldPassword: '',
        accountPassword: '',
        confirmPassword: '',
      },
      rules: {
        oldPassword: [
          { validator: validateOldPassword, trigger: 'blur' },
        ],
        accountPassword: [
          { validator: validatePassword, trigger: 'blur' },
          { min: 6, max: 64, message: '密码最小长度为6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: checkConfirmPassword, trigger: 'blur' },
          { min: 6, max: 64, message: '密码最小长度为6位', trigger: 'blur' }
        ],
      },
      isCollapse: false,
      lang: "zh",
      langOptions: [
        { label: "中文", value: "zh" },
        { label: "繁體", value: "tw" },
        { label: "English", value: "en" },
      ]
    }
  },
  beforeCreate() {
    // console.log('beforeCreate++++++', this);

  },
  created() {
    // console.log('created++++++');
  },
  beforeMount() {
    this.lang = getItem('lang') || 'zh';
    // console.log('beforeMount++++++');
  },
  async mounted() {
    // debugger
    await this._initNav();
    // console.log('mounted++++++');
  },
  computed: {
    loading() {
      // console.log('this.$store.state.loading', this.$store.state.loading);
      return this.$store.state.loading;
    },
    langText() {
      let result = {};
      for (const option of this.langOptions) {
        if (option.value == this.lang) {
          result = option;
        }
      }
      return result.label;
    }
  },
  methods: {
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    navTo(url) {
      this.$router.push(url);
    },
    handleCommand(command) {
      console.log('command', command);
      switch (command) {
        case 'signOut':
          this.$confirm('您确定要退出系统吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            signOut();
          }).catch(() => {

          });
          break
        case 'updatePassword':
          this.openUpdatePassword();
          break;

        default:
          break
      }
    },
    async _initNav() {
      this.user = getItem('user') || {};
      // 获取菜单
      try {
        let _menuList = [];
        let _menuResult = menuData;
        setItem('navResource', menuData || []);
        for (let i = 0; i < _menuResult.length; i++) {
          let _menu = _menuResult[i];
          let _menuData = {
            id: _menu.PurviewId,
            path: _menu.PageUrl,
            name: _menu.PurviewName,
            value: _menu.PurviewName,
            index: '' + _menu.PurviewId,
            icon: _menu.icon || 'el-icon-menu',
          };
          if (_menu.Childs && _menu.Childs.length > 0) {
            _menuData.children = [];
            for (let j = 0; j < _menu.Childs.length; j++) {
              let _childMenu = _menu.Childs[j];
              _menuData.children.push({
                id: _childMenu.PurviewId,
                path: _childMenu.PageUrl,
                name: _childMenu.PurviewName,
                value: _childMenu.PurviewName,
                index: '' + _childMenu.PurviewId,
                icon: _childMenu.icon || '',
              });
            }
          }
          _menuList.push(_menuData);
        }
        this.navResource = _menuList;
        console.log("_initNav ~ this.navResource:", this.navResource)
        // console.log('--------------------', this.navResource);
        // console.dir(_menuList, { depth: null });
      } catch (e) {
        console.log('--------------------error------');
        this.$message.warning(e && e.message || '菜单获取失败');
      }
      let currentRoutePath = this.$router.currentRoute.path;
      this.activeMenu = this.getActiveMenu(currentRoutePath, this.navResource);
    },

    getActiveMenu(currentRoutePath, navResource) {
      let result = '';
      for (let index = 0; index < (navResource || []).length; index++) {
        const nav = navResource[index]
        if (nav.path === currentRoutePath) {
          return nav.index;
        }
        if (nav.children && nav.children.length > 0) {
          result = this.getActiveMenu(currentRoutePath, nav.children);
          if (result) {
            return result;
          }
        }
      }
      return result;
    },

    openUpdatePassword() {
      this.dialogFormVisible = true;
    },

    cancelUpdatePassword() {
      this.dialogFormVisible = false;
      this.ruleForm = {
        oldPassword: '',
        accountPassword: '',
        confirmPassword: '',
      };
    },

    async sureUpdatePassword() {
      try {
        this.$refs['ruleForm'].validate(async(valid) => {
          if (valid) {
            let req = {
              accountPassword: this.ruleForm.accountPassword,
              oldPassword: this.ruleForm.oldPassword,
            }
            this.$message.success('修改密码成功');
            this.cancelUpdatePassword();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } catch (error) {
        this.$message.warning(error && error.message || '修改密码失败');
      }
    },

    handleCollapse(collapse) {
      this.isCollapse = collapse;
    },

    async switchLang(lang = 'tw') {
      let currentLang = getItem('lang')
      try {
        setItem('lang', lang)
        this.lang = lang;
        this.$i18n.locale = lang;
        this._initNav();
        this.$message.success(this.$t('switchLang'))
        this.pageKey++;
      } catch (error) {
        setItem('lang', currentLang)
        this.$message.warning(error.message)
      }
    },
  }

}
</script>

<style lang="scss">
#dashboard {
  height: 100%;
}

.app-container {
  height: 100%;

  .app-header {
    background-color: rgb(84, 92, 100);
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;

    .header-left {
      .logo-wrap {
        width: 170px;
        .logo {
          width: 110px;
          margin-left: 12px;
        }
      }

      .collapse-wrap {
        display: flex;
        align-items: center;
        i {
          font-size: 22px;
        }
      }
    }

    .header-right {
      width: 300px;
      text-align: right;

      .lang-text {
        color: #fff;
        padding: 0 10px;
      }
    }

    .header-icon {
      color: #fff;
    }
  }

  .app-aside {
    width: auto !important;
    overflow-x: hidden;

    .el-menu-vertical-demo {
      width: 190px;
      .el-menu-item {
        height: 46px;
        line-height: 46px;
      }
      .el-submenu .el-menu-item {
        height: 40px;
        line-height: 40px;
      }
      .el-submenu__title {
        height: 46px;
        line-height: 46px;
      }
    }

    .el-menu--collapse {
      width: 64px;

      .el-submenu__title > span {
        display: none;
      }

      .el-submenu__icon-arrow {
        margin-top: -6px;
        right: 10px;
      }
    }
    
  }

  .app-main {
    background: #f2f2f2;
  }
}
</style>
